using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using StarkSDKSpace;
using TTSDK;
using TTSDK.UNBridgeLib.LitJson;

public class AdsManager : MonoBehaviour
{
    string rewardeVideoId= "4bvjljt9lp96jkhh0g";
     string bannerAdId= "4509j48g9ijd309e02";
     string interstitialAdId= "1965a2a102eig130pg";

    
    private StarkAdManager.BannerAd m_bannerAd= null;
    private StarkAdManager.InterstitialAd m_interstitialAd= null;
    private StarkAdManager.BannerStyle m_style = new StarkAdManager.BannerStyle();
    
    private float adModuleStartTime;
    private float lastAdShowTime = 0f;
    private const float adCooldown = 30f;
    
    private StarkAdManager starkAdManager;
    private static AdsManager _instance;
    public static AdsManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new GameObject("AdsManager").AddComponent<AdsManager>();
                DontDestroyOnLoad(_instance.gameObject);
            }

            return _instance;
        }
    }
    public void Awake()
    {
        _instance = this;
        DontDestroyOnLoad(_instance.gameObject);
        
        if (Application.isEditor)
            MockSetting.OpenAllMockModule();
        starkAdManager = StarkSDK.API.GetStarkAdManager();
        adModuleStartTime = Time.time;
        
        TT.InitSDK();
        SendActive();
        ShowBannerAd(bannerAdId,60,ErrBack,LoadBack);
    }

    public void RewardVideoAd(Action<bool> callback) //直接调用奖励视频
    {
        ShowVideoAd(rewardeVideoId, callback,null);
        lastAdShowTime = Time.time;
        
    }
    public void ShowVideoAd( string videoAdId,Action<bool> callback ,Action <int,string> errorCallback )
    {
        if (videoAdId != "0")
        {
            if(starkAdManager != null)
            {
                starkAdManager.ShowVideoAdWithId(videoAdId,callback,errorCallback);
            }
        }
        else
        {
            Debug.Log("接入激励广告能力但未输入广告ID");
        }
    }
    
    public void ShowBannerAd(string BannerId,int time,Action<int,string> errorCallback,Action loadedCallback)
    {
        if (BannerId!="0")
        {
            m_style.width = 320;
            m_style.left = 10;
            m_style.top = 100;
            m_bannerAd =starkAdManager.CreateBannerAd(BannerId, m_style, time,
                errorCallback, loadedCallback);
            m_bannerAd.Show();
        }
        else
        {
            Debug.Log("接入Banner广告能力但未输入广告ID");
        }
    }

    public void ShowInterAdNow() //直接调用插屏视频
    {
        if (interstitialAdId!="0")
        {
            ShowInterstitialAd(interstitialAdId, null, null, null);
        }
    }
    
    
    public void ShowInterstitialAd(string InterstitialId, Action<int, string> errorCallback,Action closeCallback, Action loadedCallback)
    {
        if (InterstitialId!="0")
        {
            if (starkAdManager != null)
            {
                if (Time.time - adModuleStartTime < 20f)
                {
                    return;
                }

                if (Time.time - lastAdShowTime < adCooldown)
                {
                    return;
                }
                m_interstitialAd = starkAdManager.CreateInterstitialAd(InterstitialId,errorCallback,
                    closeCallback,loadedCallback);
                m_interstitialAd.Load();
                StartCoroutine(ShowAdAfterDelay());
            }
        }
        else
        {
            Debug.Log("接入插屏广告能力但未输入广告ID");
        }
    }
    
    private IEnumerator ShowAdAfterDelay()
    {
        if (m_interstitialAd == null) yield break;
        m_interstitialAd.Show();  //显示
        lastAdShowTime = Time.time;
        yield return null;
    }
    
    void ErrBack(int code, string msg)
    {
        Debug.Log(code+" "+msg);
    }
    void CloseBack()
    {
        Debug.Log("关闭广告");
    }
    void LoadBack()
    {
        Debug.Log("读取");
    }

    public void SideBarGo()
    {
        var data = new JsonData()
        {
            ["scene"] = "sidebar", 
        };
        TT.NavigateToScene(data,null,null,null);
    }
    
    #region 激活
    public void SendActive()
    {
        TTSDK.LaunchOption launchOpt = TT.GetLaunchOptionsSync();
        var cal = launchOpt.Query.FirstOrDefault(kv => kv.Key == "clickid").Value;
        object str = new
        {
            event_type = "active",
            context = new
            {
                ad = new { callback = cal }
            },
            timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
        };
        HttpManager.PostRequest(str, "/api/v2/conversion");
    }
    #endregion

    #region 关键行为
    public void SendAddiction()
    {
        TTSDK.LaunchOption launchOpt = TT.GetLaunchOptionsSync();
        var cal = launchOpt.Query.FirstOrDefault(kv => kv.Key == "clickid").Value;
        object str = new
        {
            event_type = "game_addiction",
            context = new
            {
                ad = new { callback = cal },
            },
            original_events = new
            {
            },
            timestamp = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds()
        };
        HttpManager.PostRequest(str, "/api/v2/conversion");
    }
    #endregion
    
}
